<?php
/**********************************************************
 		提现单据审核流程
 **********************************************************/
namespace src\logic\workflow;
use classlib\input;
use src\logic\Cadmin;
use src\logic\lpaypal;
use src\logic\lconfig;
use src\logic\lsitemsg;
use classlib\core as C;
use src\logic\lstripepay;
use src\logic\workflow\doc_basic;
class doc_deposit extends doc_basic {
	//系统申请
	public function node1_submit(&$state) {
		return '0';
	}
	//运营审核
	public function node2_submit(&$state) {
		$orm  = C\model::load('pro.pl.withdraw');
		$data = $orm->get_item(array('executeid'=>$state['executionid']));
		//提交请求的话更新薪资修正之后的数值
		if (strcasecmp('post', $this->method()) == 0) {
			$disname = \src\logic\Cadmin::operator();
			$remark  = input::get_post('remark');
			if ($data) {
				$notes  = $remark.'<-'.$data['remark'];
				$field  = array('memo'=>$notes, 'stime'=>C\config::$nowtime, 'opuser'=>$disname);
				//审核通过的话 记录记录登记
				if ($state['status'] == 6) {
					$field['status'] = 1;
					$field['state']  = 0;
					$orm->save($data['id'], $field);
				} else {
					//拒绝的时候发送消息提醒
					self::donotify($data, $remark);
					$field['status'] = 2;
					$orm->save($data['id'], $field);
					$userid= \src\logic\Cadmin::CREATEOR_USERID;
					$data  = array('stopuserid'=>$userid, 'stopusername'=>$disname, 'remark'=>'[System]',
							'status'=>\src\logic\workflow\doc_executor::TERMINATE, 'stoptime'=>C\config::$nowtime);
					C\model::load('main.proc.execution')->save($state['executionid'], $data);
				}
			}
		}
		return '0';
	}
	
	//财务审核
	public function node3_submit(&$state) {
		$orm  = C\model::load('pro.pl.withdraw');
		$data = $orm->get_item(array('executeid'=>$state['executionid']));
		//提交请求的话更新薪资修正之后的数值
		if (strcasecmp('post', $this->method()) == 0) {
			$disname = \src\logic\Cadmin::operator();
			$remark  = input::get_post('remark');
			if ($data) {
				$remark = $remark.'<-'.$data['remark'];
				$field  = array('remark'=>$remark, 'stime'=>C\config::$nowtime, 'operator'=>$disname);
				//审核通过的话 记录记录登记
				if ($state['status'] == 6) {
					$field['state']  = 1;
					$orm->save($data['id'], $field);
					self::dotransfer($data);
				} else {
					$field['status'] = 0;
					$field['state']  = 2;
					$orm->save($data['id'], $field);
				}
			}
		}
		return '-1';
	}
	
	//提现申请被拒绝的话发送消息提醒
	public static function donotify($data, $remark) {
		$lang  = C\lang::inst('web');
		$money = $data['money'] / lconfig::CANRATIO;
		$title = $lang->get('sitemsg', '80079');
		$msg   = $lang->txt('sitemsg', '80080', $money, $remark);
		lsitemsg::send($title, $msg, $data['userid'], 0, $data['userid']);
		//提现失败给客户端发push提醒
		$title = $lang->get('pushmsg', '90000');
		$msg   = $lang->txt('pushmsg', '90001', $money, $remark);
		lsitemsg::push($data['userid'], $title, $msg, 104);				
	}
	
	//这里处理转账的业务逻辑
	public static function dotransfer($data) {
		$view  	 = C\view::inst('json');
		$payment = C\model::load('pro.pl.payment')->get_one($data['userid']);
		$anchor  = C\model::load('pro.pl.anchor')->get_one($data['userid']);
		if (!$payment || !$anchor || $data['paystate'] != 0 || $data['type'] != 1) {
			$msg = '订单审核，订单状态/类型不匹配:';
			Cadmin::log2db($msg.C\view::inst('xml')->array2xml($data));
			$view->assign_error(1, '订单状态异常[Order Status Invalid]');
		}
		//余额不足的时候 不能审核发送新币
		if ($anchor['lastcoins'] < $data['coins']) {
			$msg = '订单审核，订单余额不足:';
			Cadmin::log2db($msg.C\view::inst('xml')->array2xml($data));
			$view->assign_error(1, '主播提现余额不足[Order Balance Not Enough]');
		}
		$user = C\model::load('pro.pl.userinfo')->get_one($data['userid']);
		if (!$user || $user['status'] != 1) {
			$view->assign_error(1, '账号状态异常不允许提现.[Account Status Invalid]');
		}
		if ($data['paytype'] == 1) {//银行卡支付
			if ($payment['status'] != 1) {
				$msg = '银行账号未审核[Stripe account is not verified]';
				Cadmin::log2db($msg.C\view::inst('xml')->array2xml($data));
				$view->assign_error(1, '银行账号未审核[Strip Account Is Not Verified].');
			}
			$res = lstripepay::payout($user['token'], $data['money'], $data['sn']);
			Cadmin::log2db('strippayout:'.C\view::inst('xml')->array2xml($res));
			if ($res['result'] != '000') {
				$msg = isset($res['value']['failureMessage'])? $res['value']['failureMessage']:$res['message'];
				$view->assign_error(1, 'Strip接口异常['.$msg.']');
			}
			$fields = array('lasttime'=>C\config::$nowtime, 'tranid'=>$res['value']['stripeTransferId']);
			C\model::load('pro.pl.withdraw')->save($data['id'], $fields);
		} else { //paypal类型
			if (empty($payment['paypal'])) {
				$view->assign_error(1, '主播未绑定Paypal[Paypal Not Binded].');
			}
			$res = lpaypal::payout($user['token'], $payment['paypal'], $data['money'], $data['sn']);
			if ($res['result'] != '000') {
				$view->assign_error(1, 'Paypal接口异常['.$res['message'].']');
			}
			$db  = C\model::load('pro.pl.withdraw')->get_orm()->get_parser();
			$db->begin_transaction();
			try {
				//更新奖金DB信息
				$table = C\model::load('pro.pl.withdraw')->get_table();
				$sql   = sprintf('update %s set lasttime=%d, paystate=1, tranid="%s" where id=%d',
						$table, C\config::$nowtime, $res['value']['paypalTransactionId'], $data['id']);
				$db->execute($sql);
				$table = C\model::load('pro.log.anchor')->get_table();
				$sql   = sprintf('update %s set withdraw=withdraw+%d, depositcoins=depositcoins+%d,'.
					' lastcoins=lastcoins-%d, lastwithdraw=%d where userid=%d',
					$table, $data['money'], $data['coins'], $data['coins'], $data['money'], $data['userid']);
				$db->execute($sql);
			} catch (\Exception $e) {
				$db->rollback();
				\classlib\logger::inst()->write($e->getMessage());
				$view->assign_error(1, 'DB处理业务失败['.$e->getMessage().']');
			}
			$db->commit();
			C\model::load('pro.pl.anchor')->set_ver();
			C\model::load('pro.pl.withdraw')->set_ver();
			//发送站内信通知
			$money = $data['money'] / lconfig::CANRATIO;
			$title = $lang->get('sitemsg', '80074');
			$msg   = $lang->txt('sitemsg', '80075', $money);
			lsitemsg::send($title, $msg, $data['userid'], 0, $data['userid']);
		}
	}
}
